package com.yale.springbootsecuritymd5.utils;

/**
 * Created by yangyibo on 17/2/7.
 */

import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密工具
 *
 */
public class MD5Util {

    private static final String SALT = "tamboo";

    public static String encode(String password) {
        password = password + SALT;
        MessageDigest md5 = null;
        try {
            // 生成一个MD5加密计算摘要
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        char[] charArray = password.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }

            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    /**利用MD5进行加密
     * @param str  待加密的字符串
     * @return  加密后的字符串
     * @throws NoSuchAlgorithmException  没有这种产生消息摘要的算法
     * @throws UnsupportedEncodingException
     */
    public static String EncoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //确定计算方法
        MessageDigest md5=MessageDigest.getInstance("MD5");
        BASE64Encoder base64en = new BASE64Encoder();
        //加密后的字符串
        String newstr=base64en.encode(md5.digest(str.getBytes("utf-8")));
        return newstr;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(MD5Util.encode("abel"));
        System.out.println("---------------------------------------");
        System.out.println(MD5Util.EncoderByMd5("abel"));
        System.out.println("--------------------encrypt-------------------");
        System.out.println(MD5Utils.encrypt("abel"));
        System.out.println("--------------------getMD5-------------------");
        System.out.println(MD5Utils.getMD5("abel".getBytes()));
        System.out.println("--------------------MD5Encode-------------------");
        System.out.println(MD5Utils.MD5Encode("a6cd39ee5b1d8276f6bc716b3f7881b7", "MD5"));

    }
}